#include "mountftp.h"
#include <QString>
#include <QUrl>
#include <QDebug>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

MountFtp::MountFtp() {}
MountFtp::~MountFtp() = default;

void MountFtp::mountFtp(QString urlStr, QString userName, QString pwd, QString path)
{
    m_isMount = true;
    killProcess();
    QUrl url(urlStr);
    int uid = getuid();
    QString common = "curlftpfs -o rw,allow_other,uid=" + QString::number(uid) + " " + url.scheme() + "://" + userName
                     + ":" + pwd + "@" + url.host() + ":" + QString::number(url.port()) + " " + path;
    startCommand(common);
}
void MountFtp::umountFtp(QString path)
{
    m_isMount = false;
    killProcess();
    QString common = "umount -f " + path;
    startCommand(common);
}

void MountFtp::startCommand(QString common)
{
    qInfo() << common;
    QProcess *process = new QProcess(this);
    process->start(common);
    connect(process, &QProcess::readyReadStandardError, this, [=]() {
        QString errOutput = process->readAllStandardError();
        qInfo() << errOutput;
        if (!errOutput.isEmpty()) {
            Q_EMIT sigMountError(m_isMount, errOutput);
        }
        m_isMount = true;
        process->deleteLater();
    });
}

void MountFtp::killProcess()
{
    static const char *cmd = "ps -aux | /var/lib/mult/";

    FILE *fp = popen(cmd, "r");
    if (fp == NULL) {
        qCritical() << "exec ps -aux | /var/lib/mult/ command fail !";
        return;
    }

    char buf[1024];
    memset(buf, '\0', sizeof(buf));
    while (!feof(fp)) {
        fgets(buf, sizeof(buf), fp);
        QString item(buf);
        memset(buf, '\0', sizeof(buf));

        if (item.isEmpty()) {
            continue;
        }

        if (item.contains("grep")) {
            continue;
        }
        QStringList itemList = item.trimmed().split(' ');
        itemList.removeAll("");
        QString info = itemList.value(1);
        bool ok = true;
        info.toLongLong(&ok);
        if (ok) {
            QString common = QString("kill -9 ") + info;
            QProcess::startDetached(common);
        }
    }

    pclose(fp);
}